import {SocketConstructor, SocketEvent} from "@/units/socket/CocketType";

/**
 * Websocket类
 */
export default class Socket {

    /**
     * WebSocket实例
     */
    ws?: WebSocket

    /**
     * websocket事件
     */
    event?: SocketEvent

    /**
     * WebSocket配置
     */
    config: SocketConstructor

    /**
     * 在线状态
     */
    line: boolean = false

    constructor(conf: SocketConstructor, event?: SocketEvent) {
        this.config = {
            url: conf.url,
            is_reconnect: (conf?.is_reconnect === undefined || conf?.is_reconnect === true),
            reconnectNum: (typeof conf?.reconnectNum === 'number') ? conf.reconnectNum : 5,
        }
        if (event) {
            this.event = event
        }
    }

    /**
     * 链接
     */
    connection(url: string = '') {
        this.ws = new WebSocket(url ? url : this.config.url)

        /**
         * 链接成功事件
         */
        if (this.event?.onopen) {
            this.ws.onopen = this.event.onopen
        }
        //链接失败事件
        if (this.event?.onerror) {
            this.ws.onerror = this.event.onerror
        }
        //消息推送事件
        if (this.event?.onmessage) {
            this.ws.onmessage = this.event.onmessage
        }
        //链接关闭事件
        if (this.event?.onclose) {
            this.ws.onclose = this.event.onclose
        }
    }


    /**
     * 发送消息
     */
    send(message: object) {
        this.ws?.send(JSON.stringify(message))
    }


    /**
     * 断开连接
     */
    close() {
        if (this.ws) {
            this.ws.close()
        }
    }

}